package com.core.shared.http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

public class HttpUtil {

	public static String connectURL(String sendsmsaddress) {
		String rec_string = "";
		URL url = null;
		HttpURLConnection urlConn = null;
		try {
			/** URL连接设置 */
			url = new URL(sendsmsaddress); // 根据数据的发送地址构建URL
			urlConn = (HttpURLConnection) url.openConnection(); // 打开链接
			urlConn.setConnectTimeout(30000); // 链接超时设置为30秒
			urlConn.setReadTimeout(30000); // 读取超时设置30秒
			urlConn.setRequestMethod("GET"); // 链接相应方式为get
			urlConn.setDoOutput(true);
			urlConn.setDoInput(true);

//			OutputStream out = urlConn.getOutputStream();
//			out.write(commString.getBytes("UTF-8"));
//			out.flush();
//			out.close();

			/** 读取返回结果 */
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					urlConn.getInputStream(), "UTF-8"));
			StringBuffer sb = new StringBuffer();
			int ch;
			while ((ch = rd.read()) > -1) {
				sb.append((char) ch);
			}

			rec_string = sb.toString().trim();
			rec_string = URLDecoder.decode(rec_string, "UTF-8");
			rd.close();
			return rec_string;
		} catch (Exception e) {
			e.printStackTrace();
			return "exception";
		} finally {
			/** 关闭url连接 */
			if (urlConn != null) {
				urlConn.disconnect();
			}
		}
	}
}
